/*
 * Copyright (c) 2014, Julien Bernard
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */
#include <mm/accessibility.h>

#include <mm/invert.h>

namespace mm {

  binarymap accessibility::operator()(const binarymap& src) {
    binarymap visited = invert()(src);

    position best_pos{0, 0};
    binarymap::size_type best_count = 0;

    for (auto x : visited.x_range()) {
      for (auto y : visited.y_range()) {
        position pos{x, y};

        if (visited(pos)) {
          continue;
        }

        binarymap::size_type count = visited.walk(pos, nullptr);

        if (count > best_count) {
          best_pos = pos;
          best_count = count;
        }
      }
    }

    visited = invert()(src);

    binarymap map(src.width(), src.height(), false);

    map(best_pos) = true;
    visited.walk(best_pos, [&map](position pos) {
      map(pos) = true;
    });

    return map;
  }

}
